package com.ly.mp.busicen.rule.flow.action.plugin;

import static com.ly.mp.busicen.rule.XruleStrUtils.splitJKH;
import static com.ly.mp.busicen.rule.XruleStrUtils.splitParam;
import static com.ly.mp.busicen.rule.XruleStrUtils.splitXKH;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.ly.mp.busicen.rule.flow.FlowSpelUtil;
import com.ly.mp.busicen.rule.flow.IDataVolume;
import com.ly.mp.busicen.rule.flow.IFireFlow;
import com.ly.mp.busicen.rule.flow.IFlowResultCtn;
import com.ly.mp.busicen.rule.flow.action.ActionExecuteBase;
import com.ly.mp.busicen.rule.flow.action.ActionResult;
import com.ly.mp.busicen.rule.flow.action.IAction;
import com.ly.mp.busicen.rule.flow.action.IActionResult;
import com.ly.mp.busicen.rule.flow.action.IActionResult.Signal;

public class ActionExecuteFlow extends ActionExecuteBase {
	
	Logger log = LoggerFactory.getLogger(ActionExecuteFlow.class);
	
	@Autowired
	IFireFlow fireFlow;

	@Override
	public IActionResult execute(IAction action, IDataVolume dataVolume) {
		ActionResult result = ActionResult.create();
		result.action(action.action());
		String flow = splitJKH(action.content());
		try {			
			String paramStr = splitXKH(action.content());
			Map<String, String> param = splitParam(paramStr);
			Map<String, Object> paramData = new HashMap<String, Object>();
			if (param!=null&&!param.isEmpty()) {
				param.forEach((k,v)->{
					paramData.put(k, FlowSpelUtil.spelGetData(action, v));
				});
			}
			IFlowResultCtn resultCtn = fireFlow.fire(flow, String.valueOf(action.extention().get(IAction.EXTKEY_BRAND)), paramData);
			if (resultCtn.isBreak()) {
				result.signal(Signal.BREAK);
				result.setConvertMsg(false);
				result.msg(resultCtn.breakResult().message());
				log.info("节点{}对应子流程{}执行结果为中断，提示信息为{}",action.action(),flow,result.msg());
			}else {
				result.signal(Signal.CONTINUE);
				result.msg(action.msg());
				result.nextAction(defaultNextActionCode(action, null));
				result.setData(resultCtn.exitResult());
				dataVolume.ext().put(action.action(), resultCtn.exitResult());
			}
			
		}catch (Exception e) {
			result.signal(Signal.EXCPT);
			result.excpt(e);
			log.info("节点{}对应子流程{}执行结果为异常...",action.action(),flow);
		}
		return result;
	}
	
}
